﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Threading;

namespace TheJoyOfCode.SLUploader
{
    public partial class FileUploader : UserControl, IFileUploadView
    {
        private readonly FileUploaderPresenter _presenter;

        public FileUploader()
        {
            InitializeComponent();
            _presenter = new FileUploaderPresenter(this);
            DataContext = _presenter.ViewModel;

            // TODO - correct, for animated changes to ProgressBar value
            //_presenter.ViewModel.PropertyChanged += ViewModel_PropertyChanged;
        }

        // TODO - correct, for animated changes to ProgressBar value
        //void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        //{
        //    if (e.PropertyName == "UploadedFiles")
        //    {
        //        Storyboard storyBoard = new Storyboard(); 
        //        DoubleAnimation animation = new DoubleAnimation();
        //        storyBoard.Duration = animation.Duration = new Duration(TimeSpan.FromMilliseconds(250));
        //        storyBoard.Children.Add(animation);

        //        Storyboard.SetTarget(animation, _progress);
        //        Storyboard.SetTargetProperty(animation, new PropertyPath(ProgressBar.ValueProperty));
        //        animation.To = _presenter.ViewModel.UploadedFiles;
        //        _rootGrid.Resources["progressValueAnimation"] = storyBoard;
        //        storyBoard.Begin();
        //    }
        //}

        public string Filter { get; set; }
        public string ServiceUri { get; set; }
        public bool UseDummyService { get; set; }

        public Uri DocumentUri
        {
            get
            {
                return HtmlPage.Document.DocumentUri;
            }
        }

        public bool ConfirmOverwrite(FileInfo file)
        {
            AutoResetEvent overwriteAre = new AutoResetEvent(false);
            bool confirmed = false;

            Dispatcher.BeginInvoke(delegate()
            {
                confirmed = HtmlPage.Window.Confirm(string.Format(
                    "File '{0}' already exists. Overwrite?",
                    file));
                overwriteAre.Set();
            });
            overwriteAre.WaitOne();
            return confirmed;
        }

        private void _btnUpload_Click(object sender, RoutedEventArgs e)
        {
            _presenter.Upload();
        }

        private void _btnOK_Click(object sender, RoutedEventArgs e)
        {
            _presenter.Done();
        }
    }
}
